package com.xike.pdfdemo.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.xike.pdfdemo.dto.Message;
import com.xike.pdfdemo.entity.DictData;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author xike
 * @date 2022/03/23
 */
@Component
public class PdfUtils {

    /**
     * 模板
     */
    final static String template = "templates/applying_for_volunteer_service_form_itext.pdf";
    final static String fonts_ttf = "fonts/seguisym.ttf";

    public static void generatePdf(OutputStream os, Message message, List<String> pickVolunteers, Map<String, List<DictData>> allVolunteers, List<DictData> dictData) throws IOException, DocumentException {
        InputStream templateInputStream = new ClassPathResource(template).getInputStream();

        PdfReader pdfReader = new PdfReader(templateInputStream);

        PdfStamper stamper = new PdfStamper(pdfReader, os);

        AcroFields acroFields = stamper.getAcroFields();
        acroFields.setSubstitutionFonts(Stream.of(
                BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED)
        ).collect(Collectors.toCollection(ArrayList::new)));
        BaseFont base = BaseFont.createFont(fonts_ttf, BaseFont.IDENTITY_H, false);
        acroFields.addSubstitutionFont(base);
        //填充模板中的占位符(属性名在制作模板时指定)
        acroFields.setField("name",message.getName());
        acroFields.setField("date",message.getDate());
        acroFields.setField("phone",message.getPhone());
        acroFields.setField("email",message.getEmail());
        acroFields.setField("school",message.getSchool());
        acroFields.setField("reason", message.getReason());
        acroFields.setField("speciality",message.getSpeciality());
        acroFields.setField("volunteerType",message.getVolunteerType());
        // 配置申请类型
        String volunteerTypes = buildVolunteerTypes(message.getVolunteerType(),dictData);
        acroFields.setField("volunteerTypes", volunteerTypes);
        // 配置志愿服务
        buildAllVolunteers(acroFields,allVolunteers,pickVolunteers);

        stamper.setFormFlattening(true);
        stamper.close();
    }

    /**
     * 配置志愿服务
     * @param acroFields
     * @param allVolunteers
     * @param pickVolunteers
     * @throws IOException
     * @throws DocumentException
     */
    private static void buildAllVolunteers(AcroFields acroFields, Map<String, List<DictData>> allVolunteers, List<String> pickVolunteers) throws IOException, DocumentException {
        if(allVolunteers.isEmpty() || CollectionUtils.isEmpty(pickVolunteers)){
            return;
        }
        String allOrg = "";
        String allVolunteer = "";
        for (Map.Entry<String, List<DictData>> entry : allVolunteers.entrySet()) {
            allOrg = allOrg + entry.getKey() + ":\n\n";
            List<DictData> value = entry.getValue();
            if(CollectionUtils.isEmpty(value)){
                allVolunteer = allVolunteer + "\n\n";
                continue;
            }
            String available = "";
            for(DictData dictDataResult : value){
                if(pickVolunteers.contains(dictDataResult.getDictName())){
                    available = available + "☑" + dictDataResult.getDictValue() + "  ";
                } else {
                    available = available + "☐" + dictDataResult.getDictValue() + "  ";
                }
            }
            int lineBreak = available.length() / 25;
            allVolunteer = allVolunteer + available + "\n\n";
            for (int j = 0; j < lineBreak; j++) {
                allOrg = allOrg + "\n";
            }
        }
        acroFields.setField("all_org", allOrg);
        acroFields.setField("allVolunteers", allVolunteer);
    }

    /**
     * 配置类型
     * @param volunteerType 当前类型
     * @param dictData 所有类型数据
     * @return
     */
    private static String buildVolunteerTypes(String volunteerType, List<DictData> dictData) {
        if(CollectionUtils.isEmpty(dictData) || StringUtils.isEmpty(volunteerType)){
            return "";
        }

        String volunteerTypes = "";
        // 换行位置
        int lineBreak = dictData.size()/2;
        int i = 1;
        for(DictData data : dictData){
            String volunteer = "";
            if(volunteerType.equals(data.getDictName())){
                volunteer = volunteer + "☑";
            } else {
                volunteer = volunteer + "☐";
            }
            volunteerTypes = volunteerTypes + String.format("%-35s", volunteer + data.getRemark());
            if(lineBreak == i){
                volunteerTypes = volunteerTypes + "\n";
            }
            i++;
        }
        return volunteerTypes;
    }

}
